<?php

namespace App\Service;

use App\Model\SaMenu;
use App\Model\SaRole;
use App\Model\SaAdmin;
use App\Model\SaPermission;
use App\Exceptions\ApiException;
use Illuminate\Support\Facades\DB;

class RoleService
{
    /**
     * 根据Id获取角色信息.
     *
     * @param $id
     *
     * @return array|bool
     */
    public static function getInfoById($id)
    {
        $data = [];
        if ($id <= 0) {
            return $data;
        }
        $info = SaRole::getInfo(['id' => $id]);
        if ($info) {
            $data       = $info;
            $permission = SaPermission::getPermission($id);
            $parent     = [];
            foreach ($permission as $val) {
                if (0 == $val['parent_id']) {
                    $parent[] = $val['id'];
                }
            }
            $menu = [];
            foreach ($permission as $value) {
                if (0 != $value['parent_id']) {
                    $key = array_search($value['parent_id'], $parent);
                    if (false !== $key) {
                        unset($parent[$key]);
                    }
                    $menu[] = $value['id'];
                }
            }
            $data['menu'] = array_merge($parent, $menu);
            $data['menu'] = array_unique($data['menu']);
        }

        return $data;
    }

    /**
     * 获取角色拥有的菜单权限.
     *
     * @param $roleId
     * @param $isAdmin
     *
     * @return |null
     */
    public static function getPermission($roleId, $isAdmin)
    {
        if (1 == $isAdmin) {
            // 超级管理员可以获取所有权限
            $list = SaMenu::getMenus(['status' => 1]);
        } else {
            $list = SaPermission::getPermission($roleId);
        }
        $tree = getTree($list);

        return ['list' => $list, 'tree' => $tree];
    }

    /**
     * 添加角色.
     *
     * @param $name
     * @param $menuIds
     * @param $createdBy
     * @param int $status
     *
     * @return mixed
     */
    public static function addRole($name, $menuIds, $createdBy, $status = 1)
    {
        // 验证参数
        throw_if(!$name, new ApiException('请输入角色名称'));
        throw_if(!$menuIds, new ApiException('请选择角色权限'));

        // 检测是否重名
        $info = SaRole::getInfo(['name' => $name]);
        throw_if($info, new ApiException('此角色已存在，请勿重复添加'));

        $menuIds    = array_unique($menuIds);
        $loginAdmin = HelperClass::getLoginAdmin();
        DB::beginTransaction();
        try {
            $role['name']         = $name;
            $role['status']       = $status;
            $role['creator_id']   = $loginAdmin['id'];
            $role['creator']      = $loginAdmin['username'];
            $roleId               = SaRole::addRole($role);

            $permission = [];
            foreach ($menuIds as $val) {
                $permission[]      = [
                    'role_id'    => $roleId,
                    'menu_id'    => $val,
                    'creator_id' => $loginAdmin['id'],
                    'creator'    => $loginAdmin['username'],
                    'created_at' => date_time_str(),
                ];
            }
            SaPermission::insert($permission);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            throw_if(true, new ApiException('操作失败，请稍后重试'));
        }

        return true;
    }

    /**
     * 编辑角色.
     *
     * @param $id
     * @param $name
     * @param $menuIds
     * @param $status
     *
     * @return mixed
     */
    public static function editRole($id, $name, $menuIds, $status)
    {
        throw_if($id <= 0, new ApiException('ID参数异常'));
        // 验证参数
        throw_if(!$name, new ApiException('请输入角色名称'));
        throw_if(!$menuIds, new ApiException('请选择角色权限'));

        // 获取被删除的角色信息
        $info = SaRole::getInfo(['id' => $id]);
        throw_if(!$info, new ApiException('数据不存在'));
        throw_if($info && 1 == $info['is_admin'], new ApiException('无权修改超级管理员'));

        $loginAdmin = HelperClass::getLoginAdmin();
        DB::beginTransaction();
        try {
            $role['name']   = $name;
            $role['status'] = $status;
            SaRole::editRole($id, $role);

            SaPermission::delPermissionByRole($id);

            $permission = [];
            foreach ($menuIds as $val) {
                $permission[]      = [
                    'role_id'    => $id,
                    'menu_id'    => $val,
                    'creator_id' => $loginAdmin['id'],
                    'creator'    => $loginAdmin['username'],
                    'created_at' => date_time_str(),
                ];
            }
            SaPermission::insert($permission);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            throw_if(true, new ApiException('操作失败，请稍后重试'));
        }

        return true;
    }

    /**
     * 删除角色.
     *
     * @param $id
     *
     * @return mixed
     */
    public static function delRoleById($id)
    {
        throw_if($id <= 0, new ApiException('ID参数有误'));

        // 获取被删除的角色信息
        $info = SaRole::getInfo(['id' => $id]);
        throw_if($info && 1 == $info['is_admin'], new ApiException('无权删除超级管理员'));

        // 验证使用该角色的管理员数量
        $adminCount = SaAdmin::getCount(['role_id' => $id]);
        throw_if($adminCount, new ApiException('有管理员使用此角色，无法删除'));

        DB::beginTransaction();
        try {
            SaRole::delRole($id);
            SaPermission::delPermissionByRole($id);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            throw_if(true, new ApiException('操作失败，请稍后重试'));
        }

        return true;
    }
}
